<template>
  <div class="score-import">
    <el-date-picker
      v-model="date"
      type="date"
      value-format="yyyy-mm-dd"
      placeholder="选择日期"
    >
    </el-date-picker>
    <div class="table">
      <el-table
        :data="tableData"
        border
        height="250"
        style="width: 100%"
      >
        <el-table-column
          fixed
          prop="name"
          label="姓名"
          width="150">
        </el-table-column>
        <el-table-column
          v-for="(item, index) in subject"
          :key="index"
          :prop="item"
          :label="item"
        >
          <template v-slot="scoped">
            <el-input size="mini" v-model="scoped.row[item]" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-button type="primary" style="margin-top: 20px;" @click="create">完成</el-button>
    </div>
  </div>
</template>

<script>
import storage from '@/utils/storage'

export default {
  name: 'score-import',
  data () {
    return {
      date: '',
      tableData: [],
      subject: []
    }
  },
  created () {
    this.initTableData()
  },
  methods: {
    initTableData () {
      const subject = storage.getItem('subject')
      const student = storage.getItem('seat').reduce((prev, item) => {
        item.forEach((colItem, colIndex) => {
          colItem.forEach((studentItem) => {
            if (studentItem.name) {
              prev.push(studentItem.name)
            }
          })
        })
        return prev
      }, [])
      student.forEach((item) => {
        const studentItem = {
          name: item
        }
        subject.forEach(subjectItem => {
          studentItem[subjectItem] = 0
        })
        this.tableData.push(studentItem)
      })
      this.subject = subject
    },
    create () {
      this.tableData.forEach((item) => {
        const score = { ...item }
        delete score.name
        this.$db.add('achievement', {
          student: item.name,
          create_time: this.date,
          score: score
        })
      })
      setTimeout(() => {
        window.location.reload()
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.score-import {
  margin: 40px 80px;
  .table {
    margin-top: 20px;
  }
}
</style>
